package com.prestamomo.vil.ppa.pmvilnet;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.prestamomo.vil.ppa.BuildConfig;
import com.prestamomo.vil.ppa.PmvilApp;
import com.prestamomo.vil.ppa.pmvilmedium.pmviluse.PmvilSpMd;
import com.prestamomo.vil.ppa.pmvilnet.pmvilutils.PmvilAnalyze;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class PmvilRetrofitHelper {

    //baseUrl
    public static String pmvilbaseUrl = "https://hk-dev-api.cashproiso.com";
    public static String pmvilWebXYUrl = "https://hk-dev-api.cashproiso.com";//
    private int pmvil_timeout = 60;

    private static volatile PmvilRetrofitHelper pmvilInstance;

    private final Retrofit.Builder pmvilRetrofitBuilder;



    public Retrofit getPmvilRetrofit() {
        return getPmvilRetrofit(null);
    }


    public Retrofit getPmvilRetrofit(String pmvilBaseUrl) {
        Retrofit pmvilRetrofits;
        if (TextUtils.isEmpty(pmvilBaseUrl)) {
            pmvilRetrofits = pmvilRetrofitBuilder.baseUrl(PmvilRetrofitHelper.pmvilbaseUrl).build();
        } else {
            pmvilRetrofits = pmvilRetrofitBuilder.baseUrl(pmvilBaseUrl).build();
        }
        return pmvilRetrofits;
    }

    private PmvilRetrofitHelper() {
//        pmvilbaseUrl = "http://192.168.2.102:8018";

        OkHttpClient.Builder okhttPmvilBuilder = new OkHttpClient.Builder();

        HttpLoggingInterceptor httpPmvilloggingInterceptor = new HttpLoggingInterceptor();
        okhttPmvilBuilder.addInterceptor(getHeaderPmvilInterceptor())
                .addInterceptor(new ResposPmvilInlnt())
                .connectTimeout(pmvil_timeout, TimeUnit.SECONDS)
                .readTimeout(pmvil_timeout, TimeUnit.SECONDS)
                .writeTimeout(pmvil_timeout, TimeUnit.SECONDS)
                .addInterceptor(httpPmvilloggingInterceptor.setLevel(BuildConfig.DEBUG?HttpLoggingInterceptor.Level.BODY:HttpLoggingInterceptor.Level.NONE))
                .sslSocketFactory(PmvilSSLSocketClient.getSSLSocketFactory(),PmvilSSLSocketClient.getX509TrustManager())
                .retryOnConnectionFailure(false);
        OkHttpClient okHttpPmvilClient = okhttPmvilBuilder.build();

        pmvilRetrofitBuilder = new Retrofit.Builder();
        pmvilRetrofitBuilder.client(okHttpPmvilClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    }

    public static PmvilRetrofitHelper getPmvilInstance() {
        Map<String,Object> pmvilReHelp = new HashMap<>();
        pmvilReHelp.put("pmvilRehwl",2);
        if (pmvilInstance == null) {
            pmvilReHelp.put("pmvilRehwl",0);
            synchronized (PmvilRetrofitHelper.class) {
                if (pmvilInstance == null) {
                    pmvilReHelp.put("pmvilReKis",true);
                    pmvilInstance = new PmvilRetrofitHelper();
                }else {
                    pmvilReHelp.put("pmvilReKis",false);
                }
            }
        }else {
            pmvilReHelp.put("pmvilRehwl",1);
        }
        if((int)pmvilReHelp.get("pmvilRehwl")!=2){
            pmvilReHelp.clear();
            pmvilReHelp = null;
        }
        return pmvilInstance;
    }


    private Interceptor getHeaderPmvilInterceptor() {
        return chain -> {
            Request originalPmvilRequest = chain.request();
            Request.Builder reqPmvilBuilder = originalPmvilRequest.newBuilder();
            reqPmvilBuilder.method(originalPmvilRequest.method(), originalPmvilRequest.body());
            reqPmvilBuilder.addHeader("Content-Type", "text/plain;charset=utf-8").build();
            reqPmvilBuilder.addHeader("pcash", BuildConfig.APPLICATION_ID).build();//packageName
            reqPmvilBuilder.addHeader("gpsId", PmvilApp.pmvilGoogleAdid);//gpsId
            reqPmvilBuilder.addHeader("pmlvilSekin", "2002");
            reqPmvilBuilder.addHeader("pmvilNike", "pickNils");
            reqPmvilBuilder.addHeader("IFORGJYES", setPmvilHeaders()).build();//headers
            Request requestPmvils = reqPmvilBuilder.build();
            return chain.proceed(requestPmvils);
        };
    }


    private  String setPmvilHeaders() {
        Map<String, Object> headerPmvilMap = new HashMap<>();
        headerPmvilMap.put("pmvilseww", 1089);
        headerPmvilMap.put("qwgoqiwe", BuildConfig.VERSION_NAME);//version
        headerPmvilMap.put("mgrjm", PmvilApp.getPmAdjustTrsName());//sourceChannel
        headerPmvilMap.put("pcash", BuildConfig.APPLICATION_ID);//packageName--pcash
        headerPmvilMap.put("ahfaw", PmvilApp.getPmAdjustAdid());//adId
        headerPmvilMap.put("zgpkgai", 886);//countryCode
        String userPmvilId = (String) PmvilSpMd.getPmvaParam(PmvilApp.getPmvilApss(),"pmvil_userId_pm","");
        String pmvilUuId = (String) PmvilSpMd.getPmvaParam(PmvilApp.getPmvilApss(),"pmvil_uuId_pm","");
        if (!TextUtils.isEmpty(userPmvilId)) {
            headerPmvilMap.put("brlsu", userPmvilId);//userId
            headerPmvilMap.put("mkndqrjgm", pmvilUuId);//uuId
        }
        return  PmvilAnalyze.analyzePmvilCopy(new Gson().toJson(headerPmvilMap),true);
    }

    class ResposPmvilInlnt implements Interceptor{
        @NonNull
        @Override
        public Response intercept(@NonNull Chain pmvilChain) throws IOException {

            Request pmvilRequest = pmvilChain.request();
            Response pmvilResponse = pmvilChain.proceed(pmvilRequest);
            String string = pmvilResponse.body().string();
            Log.e("--",string);
            String newPmvilResponseBodyStr = PmvilAnalyze.decryptPmvilCopy(string);
            Log.e("newPmvilResponseBodyStr",newPmvilResponseBodyStr);
            pmvilResponse = pmvilResponse.newBuilder().body(ResponseBody.create(MediaType.parse("text/plain;charset=UTF-8"), newPmvilResponseBodyStr)).build();
            return pmvilResponse;
        }
    }
}
